package org.grayrabbit.cloud.web.context;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.lang.StringUtils;
import org.grayrabbit.cloud.core.Context;
import org.grayrabbit.cloud.core.application.BizApplication;
import org.grayrabbit.cloud.core.module.ModuleConstructException;
import org.grayrabbit.cloud.core.module.SpringContextUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.WebApplicationContext;


public class ContextListener implements ServletContextListener {
	private static final Logger logger = LoggerFactory.getLogger(ContextListener.class);
	/**
	 * web.xml中的配置服务器xml配置文件的参数名
	 */
	private static final String CONFIG_LOCATION_SERVER_PARAM = "cloudServerConfigLocation";
	
	/**
	 * web.xml中的配置客户器xml配置文件的参数名
	 */
	private static final String CONFIG_LOCATION_CLIENT_PARAM = "cloudClientConfigLocation";
	
	@Override
	public void contextDestroyed(ServletContextEvent evt) {
		
	}

	@Override
	public void contextInitialized(ServletContextEvent evt) {
		String serverConfg = evt.getServletContext().getInitParameter(CONFIG_LOCATION_SERVER_PARAM);
		logger.info("Cloud server config is {}",serverConfg);
		if(evt.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)!=null){
			Context<String, ApplicationContext> context = SpringContextUtil.newInstance();
			context.setValue(SpringContextUtil.WEB_APPLICATION_KEY, (ApplicationContext)evt.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE));
		}
		if(StringUtils.isNotBlank(serverConfg)){
			try {
				new BizApplication(serverConfg,true).run();
			} catch (ModuleConstructException e) {
				logger.error("Cloud server strart failure.",e);
			}
		}
		
		String clientConfg = evt.getServletContext().getInitParameter(CONFIG_LOCATION_CLIENT_PARAM);
		logger.info("Cloud client config is {}",clientConfg);
		if(StringUtils.isNotBlank(clientConfg)){
			try {
				new BizApplication(clientConfg,false).run();
			} catch (ModuleConstructException e) {
				logger.error("Cloud client strart failure.",e);
			}
		}
	}
}
